<?php 
namespace App\Http\Models;

use App\Http\Models\GameCodeCacheModel\GameCodeModel;
use Illuminate\Database\Eloquent\Model;

class LotteryPrizeModel extends Model
{
    const STATUS_ACTIVE = 1;
    const STATUS_DELETE = 0;

    protected $connection = 'db_main';
    protected $isSharding = 1;
    protected $table = 'wp_sdk_lottery_prize';

    protected $fillable = ['appid', 'lot_id', 'lot_name', 'lot_count', 'lot_consume', 'probability', 'lot_desc', 'lot_winning_tips', 'lot_url', 'lot_type', 'lot_code_setting', 'status', 'create_time', 'modify_time', 'prizes_link'];

    public $timestamps = false;

    private static $_prizeStatus = array(
        self::STATUS_ACTIVE   => '正常',
        self::STATUS_DELETE  => '下架'
    );

    //抽奖类型
    const LOT_TYPE_RAFFLE   = 0;    //  默认奖品
    const LOT_TYPE_EXCHANGE = 1;    //  绑定兑换码
    const LOT_TYPE_RANK     = 2;    //  排行榜
    const LOT_TYPE_NONE     = 3;	//  无
    const LOT_TYPE_FORM     = 4;	//  报名表单
    const LOT_TYPE_PPT      = 5;    //  PPT
    const LOT_TYPE_CARD     = 6;    //  企业名片
    const LOT_TYPE_CROWD    = 7;    //  众筹
    const LOT_TYPE_VOTE     = 8;	//  投票
    const LOT_TYPE_CROWDRAFFLE   = 9; //  众筹抽奖
    const LOT_TYPE_CROWDEXCHANGE = 10;//  众筹奖券
    const LOT_TYPE_COUPON   = 11;   //  微信代金券
    const LOT_TYPE_THIRD    = 12;   //  第三方发奖
    const LOT_TYPE_THIRD_ZC = 13;   //  众筹第三方发奖
    const LOT_TYPE_VOTEBAOMING   = 14;   //  投票报名
    const LOT_TYPE_VOTERANK      = 15;   //  投票排行榜

    const TYPE_RAFFLE_SIGNED_RAFFLE     = 16;//签到抽奖
    const TYPE_RAFFLE_SIGNED_EXCHANGE   = 17;//签到奖券
    const LOT_TYPE_CROWD1_RAFFLE        = 18;    //  众筹一抽奖
    const LOT_TYPE_CROWD1_THIRD         = 19;    //  众筹一第三方

    const LOT_TYPE_REDPACK  = 20;    //  微信红包
    const LOT_TYPE_INDIANA  = 21; //幸运众筹
    const LOT_TYPE_CREDIT   = 22; //积分

    private static $_lotType = array(
        self::LOT_TYPE_RAFFLE,
        self::LOT_TYPE_EXCHANGE,
        self::LOT_TYPE_RANK,
        self::LOT_TYPE_NONE,
        self::LOT_TYPE_FORM,
        self::LOT_TYPE_PPT,
        self::LOT_TYPE_CARD,
        self::LOT_TYPE_VOTE,
        self::LOT_TYPE_CROWD,
        self::LOT_TYPE_CROWDRAFFLE,
        self::LOT_TYPE_CROWDEXCHANGE,
        self::LOT_TYPE_COUPON,
        self::LOT_TYPE_THIRD,
        self::LOT_TYPE_THIRD_ZC,
        self::LOT_TYPE_VOTEBAOMING,
        self::LOT_TYPE_VOTERANK,
        self::TYPE_RAFFLE_SIGNED_RAFFLE,
        self::TYPE_RAFFLE_SIGNED_EXCHANGE,
        self::LOT_TYPE_CROWD1_RAFFLE,
        self::LOT_TYPE_CROWD1_THIRD,
        self::LOT_TYPE_REDPACK,
        self::LOT_TYPE_INDIANA,
        self::LOT_TYPE_CREDIT
    );

    private static $_lotTypeName = array(
        self::LOT_TYPE_RAFFLE  => 'raffle',
        self::LOT_TYPE_EXCHANGE=> 'exchange',
        self::LOT_TYPE_RANK    => 'rank',
        self::LOT_TYPE_NONE    => 'none',
        self::LOT_TYPE_FORM    => 'form',
        self::LOT_TYPE_PPT     => 'ppt',
        self::LOT_TYPE_CARD    => 'card',
        self::LOT_TYPE_VOTE    => 'vote',
        self::LOT_TYPE_CROWD   => 'crowd',
        self::LOT_TYPE_CROWDRAFFLE     => 'crowdraffle',
        self::LOT_TYPE_CROWDEXCHANGE   => 'crowdexchange',
        self::LOT_TYPE_THIRD     => 'third',
        self::LOT_TYPE_THIRD_ZC  => 'thirdzc',
        self::TYPE_RAFFLE_SIGNED_RAFFLE    => 'signedraffle',
        self::TYPE_RAFFLE_SIGNED_EXCHANGE  => 'signedexchange',
        self::LOT_TYPE_COUPON    => 'coupon',
        self::LOT_TYPE_VOTEBAOMING => 'votebaoming',
        self::LOT_TYPE_VOTERANK    => 'voterank',
        self::LOT_TYPE_CROWD1_RAFFLE => 'crowd1raffle',
        self::LOT_TYPE_CROWD1_THIRD => 'crowd1third',
        self::LOT_TYPE_REDPACK     => 'redpack',
        self::LOT_TYPE_INDIANA => 'indiana',
        self::LOT_TYPE_CREDIT => 'credit',

    );

    private static $_lotTypeTitle = array(
        self::LOT_TYPE_RAFFLE  => '实物奖品',
        self::LOT_TYPE_EXCHANGE=> '优惠券',
        self::LOT_TYPE_RANK    => '排行榜',
        self::LOT_TYPE_NONE    => '分享',
        self::LOT_TYPE_FORM    => '表单',
        self::LOT_TYPE_PPT     => 'PPT',
        self::LOT_TYPE_CARD    => '名片',
        self::LOT_TYPE_VOTE    => '投票',
        self::LOT_TYPE_CROWD   => '众筹奖券',
        self::LOT_TYPE_CROWDRAFFLE     => '众筹抽奖',
        self::LOT_TYPE_CROWDEXCHANGE   => '众筹抽奖',
        self::LOT_TYPE_THIRD     => '第三方发奖',
        self::LOT_TYPE_THIRD_ZC  => '第三方发奖',
        self::TYPE_RAFFLE_SIGNED_RAFFLE    => '签到发奖',
        self::TYPE_RAFFLE_SIGNED_EXCHANGE  => '签到发券',
        self::LOT_TYPE_COUPON    => '优惠券',
        self::LOT_TYPE_VOTEBAOMING => '投票报名',
        self::LOT_TYPE_VOTERANK    => '投票排行榜',
        self::LOT_TYPE_CROWD1_RAFFLE => '众筹抽奖',
        self::LOT_TYPE_CROWD1_THIRD => '第三方发奖',
        self::LOT_TYPE_REDPACK     => '微信红包',
        self::LOT_TYPE_INDIANA => '幸运众筹',
        self::LOT_TYPE_CREDIT => '积分',

    );

    /**
     * 判断类型
     * @param int $type
     * @return int
     */
    public static function checkType($type = self::LOT_TYPE_RAFFLE) {
        return in_array($type, self::$_lotType) ? $type : self::LOT_TYPE_RAFFLE;
    }

    /**
     * 删除一个奖品详情
     */
    public static function delPrize($appid, $ids) {
        if(!$appid || !$ids) return false;
        $data = array(
            'lot_type'     => array('NOT IN', array(self::LOT_TYPE_REDPACK, self::LOT_TYPE_CREDIT, self::LOT_TYPE_INDIANA)),
            'status'       => self::STATUS_DELETE,
            'modify_time'  => time()
        );
        $map['appid'] = $appid;
        $map['status'] = self::STATUS_ACTIVE;
        if (!is_array($ids)) {
            $ids = array($ids);
        }
        $map['id'] = array('IN', $ids);

        return self::where($map)->update($data);

    }

    /**
     * 添加一个奖品详情
     */
    public static function addPrize($appid, $data) {
        if(!$appid || $data['id'] || !$data['lot_name'] || !$data['lot_count']) return false;
        $lot_type = self::checkType($data['lot_type']);
        $data['appid']  = $appid;
        $data['lot_id'] = 0;
        $data['lot_type'] = $lot_type;
        $data['create_time'] = time();
        $data['modify_time'] = 0;
        $data['status'] = self::STATUS_ACTIVE;
        $id = self::create($data);
        return $id;
    }

    /**
     * 同步prizes表内容
     * @param $appid
     * @param $lot_type
     * @param array $prizes
     * @return bool
     */
    public static function syncPrizes($appid, $uid, $lot_type, array $prizes) {
        if (empty($prizes)) return false;

        // 处理prize，优化新增/修改/删除方法
        $lot_type = self::checkType($lot_type);
        $onlinePrizes = self::getPrize($appid, false, false, self::STATUS_ACTIVE, array('id', 'lot_count', 'lot_code_setting', 'lot_type'));
        $onlinePrizesArr = $onlinePrizes->toArray();
        $online = array_keys($onlinePrizesArr);
        $online = $online ? $online : array();
        $offline = $update = array();

        $vipLevel = VipModel::getVipLevel($uid);

        $prize_number   = VipLevelModel::getVipPowerByDb($vipLevel, 'editor_prize_category_numbers');
        $lottery_number = VipLevelModel::getVipPowerByDb($vipLevel, 'editor_prize_numbers' );
        $prize_number = (int) $prize_number;
        $lottery_number = (int) $lottery_number;
        $lot_total = $lot_total_tmp = $delete_redpack_lot_total = $active_redpack_lot_total = 0;

        $data = array();
        foreach ($prizes as $key => $prize) {
            if($prize['lot_id'] != 0 || !$prize_number || $key < $prize_number) {
                if( $lottery_number ) {
                    $lot_total_tmp = $lot_total;
                    $lot_total += $prize['lot_count'];
                    if($lot_total > $lottery_number) {
                        if(! ($prize['lot_id'] != 0 && isset($onlinePrizes[$prize['lot_id']]) && ($onlinePrizes[$prize['lot_id']]['lot_count']==$prize['lot_count']))) {
                            $lot_count = $lottery_number-$lot_total_tmp;
                            $prize['lot_count'] = $lot_count>0 ? $lot_count : 0;
                        }
                    }
                }

                $lot_code_setting = '';
                if (!empty($prize['lot_code_setting'])) {
                    $lot_code_setting = $prize['lot_code_setting'];
                    if (is_array($lot_code_setting) || is_object($lot_code_setting)) {
                        if(isset($lot_code_setting['num'])) $lot_code_setting['num'] = $prize['lot_count'];
                        $lot_code_setting = json_encode($lot_code_setting);
                    }
                }

                $data = array(
                    'lot_name'      => $prize['lot_name'],
                    'lot_count'     => $prize['lot_count'],
                    'probability'   => $prize['probability'],
                    'lot_desc'      => $prize['lot_desc'],
                    'lot_url'       => $prize['lot_url'],
                    'prizes_link'   => $prize['prizes_link'],
                    'lot_type'      => isset($prize['lot_type']) && in_array($prize['lot_type'], array(0,1,2,3,7,9,10,12,13,18,19,20,22)) ? $prize['lot_type'] : $lot_type,
                    'lot_winning_tips'  => isset($prize['lot_winning_tips'])? $prize['lot_winning_tips']:'',
                    'lot_code_setting'  => $lot_code_setting
                );

                if($prize['lot_id'] == 0) {

                    if($data['lot_type'] == self::LOT_TYPE_REDPACK) {
                        //当奖品为微信红包时，处理奖品预存金问题
                        $lot_unit_price   = isset($prize['lot_code_setting']['lot_unit_price']) ? $prize['lot_code_setting']['lot_unit_price'] : 0;
                        $lot_amount_price = $lot_unit_price*$data['lot_count'];
                        $lot_amount_price = checkWhiteList($uid) ? $lot_amount_price*0.01 : $lot_amount_price;
                        $lot_amount_price = (float)sprintf("%.2f", $lot_amount_price);
                        if($lot_amount_price>0) {
                            $pointRet = VipModel::addItemValue($uid, 'allredpackpoint', -$lot_amount_price);
                            if(!$pointRet) continue;
                        }
                        $data['wxpay_fund'] = $lot_amount_price;
                        $active_redpack_lot_total++;
                    }

                    if($data['lot_type'] == self::LOT_TYPE_CREDIT) {
                        //当奖品为微信红包时，处理奖品预存金问题
                        $lot_unit_credit   = isset($prize['lot_code_setting']['lot_unit_credit']) ? $prize['lot_code_setting']['lot_unit_credit'] : 0;
                        $lot_amount_credit = isset($prize['lot_code_setting']['lot_amount_credit']) ? $prize['lot_code_setting']['lot_amount_credit'] : 0;
                        $lot_amount_credit = checkWhiteList($uid) ? $lot_amount_credit*0.01 : $lot_amount_credit;
                        $lot_amount_credit = (float)sprintf("%.2f", $lot_amount_credit);
                        if($lot_amount_credit>0) {
                            $pointRet = VipModel::addItemValue($uid, 'allredpackpoint', -$lot_amount_credit);
                            if(!$pointRet) continue;
                        }
                        $data['wxpay_fund'] = $lot_amount_credit;
                        $active_redpack_lot_total++;
                    }

                    //增加
                    $lot_id = LotteryPrizeModel::addPrize($appid, $data);
                    LotteryPrizeModel::writePrizeLog($appid, $lot_id, $lot_type, 'add', json_encode($prize));
                    if ($lot_id && ($data['lot_type'] == LotteryPrizeModel::LOT_TYPE_EXCHANGE || $data['lot_type'] == LotteryPrizeModel::LOT_TYPE_CROWD || $data['lot_type'] == LotteryPrizeModel::LOT_TYPE_CROWDEXCHANGE || $data['lot_type']==LotteryPrizeModel::TYPE_RAFFLE_SIGNED_EXCHANGE )) {
                        //此处需要插入到gamecode 表中
                        self::importgamecode($appid, $lot_id, $prize['lot_code_setting'], $prize['lot_count']);
                    }

                    if(!$lot_id && $data['lot_type'] == LotteryPrizeModel::LOT_TYPE_REDPACK) {
                        //创建奖品失败时，将资金退回红包账户余额中
                        if($lot_amount_price>0) {
                            $pointRet = VipModel::addItemValue($uid, 'allredpackpoint', $lot_amount_price);
                        }
                    }

                    if(!$lot_id && $data['lot_type'] == LotteryPrizeModel::LOT_TYPE_CREDIT) {
                        //创建奖品失败时，将资金退回红包账户余额中
                        if($lot_amount_credit>0) {
                            $pointRet = VipModel::addItemValue($uid, 'allredpackpoint', $lot_amount_credit);
//                             $pointRet = $vipModel->addItemValue($uid, 'allcreditpoint', $lot_amount_credit);
                        }
                    }

                } else {
                    //修改
                    $data['id'] = $prize['lot_id'];

                    if($data['lot_type'] == LotteryPrizeModel::LOT_TYPE_REDPACK) {
                        //当奖品为微信红包时，不允许修改
                        /* $update[] = $data['lot_id'];
                        continue; */

                        $changeLotCodeData = $prize['lot_code_setting'];
                        if(isset($changeLotCodeData['lot_unit_price'])) unset($changeLotCodeData['lot_unit_price']);
                        if(isset($changeLotCodeData['lot_amount_price'])) unset($changeLotCodeData['lot_amount_price']);
                        if(count($changeLotCodeData) >0 && $onlinePrizes[$prize['lot_id']]) {
                            $oldLotCodeData = json_decode($onlinePrizes[$prize['lot_id']]['lot_code_setting'], true);
                            $changeLotCodeData = array_merge($oldLotCodeData, $changeLotCodeData);
                            $data['lot_code_setting'] = json_encode($changeLotCodeData);
                        }
                        unset($data['lot_count'], $data['wxpay_fund'], $data['wxpay_refund']);
                    }

                    if($data['lot_type'] == LotteryPrizeModel::LOT_TYPE_CREDIT) {
                        //当奖品为微信红包时，不允许修改
                        /* $update[] = $data['lot_id'];
                         continue; */

                        $changeLotCodeData = $prize['lot_code_setting'];
                        if(isset($changeLotCodeData['lot_unit_credit'])) unset($changeLotCodeData['lot_unit_credit']);
                        if(isset($changeLotCodeData['lot_amount_credit'])) unset($changeLotCodeData['lot_amount_credit']);
                        if(count($changeLotCodeData) >0 && $onlinePrizes[$prize['lot_id']]) {
                            $oldLotCodeData = json_decode($onlinePrizes[$prize['lot_id']]['lot_code_setting'], true);
                            $changeLotCodeData = array_merge($oldLotCodeData, $changeLotCodeData);
                            $data['lot_code_setting'] = json_encode($changeLotCodeData);
                        }
                        unset($data['lot_count'], $data['wxpay_fund'], $data['wxpay_refund']);
                    }

                    LotteryPrizeModel::updatePrize($appid, $data);
                    LotteryPrizeLogModel::writePrizeLog($appid, $data['id'], $lot_type, 'update', json_encode($prize));
                    $update[] = $prize['lot_id'];
                }
            }
        }

        $onlineUpdate = array();
        foreach ($onlinePrizes as $onlineId => $onPrizes) {
            if(!in_array($onPrizes['lot_type'], array(LotteryPrizeModel::LOT_TYPE_REDPACK, LotteryPrizeModel::LOT_TYPE_INDIANA, LotteryPrizeModel::LOT_TYPE_CREDIT))) {
                $onlineUpdate[] = $onlineId;
            }
        }

        $offline = array_diff($onlineUpdate, $update);
        if( count($offline)>0 ) {
            LotteryPrizeModel::delPrize($appid, $offline);

            //清理lottery记录
            LotteryModel::delLottery($appid, $offline);

            //清理lottery日志记录
            LotteryLogModel::delLotteryLog($appid, $offline);

            //if ($lot_type != $lotteryPrizeModel::LOT_TYPE_EXCHANGE && $lot_type != $lotteryPrizeModel::LOT_TYPE_CROWDEXCHANGE) {
            //此处需要插入到gamecode 表中
            //$gcModel = RD('GameCode', $appid);
            $ret = GameCodeModel::delGameCode($appid, $offline);
            //}

            if ($lot_type == LotteryPrizeModel::LOT_TYPE_CROWD || $lot_type == LotteryPrizeModel::LOT_TYPE_CROWDRAFFLE || $lot_type == LotteryPrizeModel::LOT_TYPE_CROWDEXCHANGE) {
                //删除众筹记录
                CrowdFundingModel::delRecordByPrizeId($appid, $offline);
            }

            //写奖品修改日志
            foreach ($offline as $offId) {
                LotteryPrizeLogModel::writePrizeLog($appid, $offId, $lot_type, 'del', '');
            }
        }

        return true;
    }

    /**
     * 更新一个奖品详情
     */
    public static function updatePrize($appid, $data) {
        if(!$appid || !$data['id']) return false;
        $data['lot_id'] = 0;
        $data['modify_time'] = time();
        $map = array(
            'id'      => $data['id'],
            'appid'   => $appid,
            'status'  => self::STATUS_ACTIVE
        );
        self::where($map)->update($data);
    }
    /**
     * 获取所有有效的奖项
     */
    public static function getPrizeInfo($appid, $ids = false, $lot_type = self::LOT_TYPE_RAFFLE) {
        $field = array('lot_name','lot_count','lot_consume','probability','lot_desc','lot_winning_tips','lot_url','lot_type','lot_code_setting','prizes_link','status','wxpay_fund','wxpay_refund');
        return self::getPrize($appid, $ids, $lot_type, self::STATUS_ACTIVE, $field);
    }

    /**
     * 获取奖品详情
     */
    public static function getPrize($appid, $ids = false, $lot_type = self::LOT_TYPE_RAFFLE, $status = self::STATUS_ACTIVE, $fields) {
        $map['appid'] = $appid;
        if($ids) {
            if(!is_array($ids)) $map['id'] = $ids;
            else $map['id'] = array('IN', $ids);
        }
        if(false !== $lot_type) $map['lot_type'] = self::checkType($lot_type);
        if(false !== $status) $map['status'] = in_array($status, self::$_prizeStatus) ? $status : self::STATUS_ACTIVE;
        $fieldArr = array();
        $field = 'id';
        if($fields) {
            if(!is_array($fields)) {
                if(false === strpos($fields, '*')) {
                    $fieldArr = explode(',', $fields);
                } else {
                    $prizesArr = self::where($map)->get();
                    $prizes = array();
                    if($prizesArr) {
                        $projectInfo = ProjectModel::getInfoByAppid($appid);
                        $caseTempName = $projectInfo['name'];
                        foreach ($prizesArr as $prize) {
                            if($prize['lot_url'] && false === strpos($prize['lot_url'], "/play/tpl_{$caseTempName}")) {
                                $prize['lot_url'] = preg_replace("/^\/play\/(.*?)$/", "/play/tpl_{$caseTempName}/$1", $prize['lot_url']);
                            }
                            $prizes[$prize['id']] = $prize;
                        }
                    }

                    return $prizes;
                }
            } else $fieldArr = $fields;
            $fieldArr = array_diff($fieldArr, array("id", "lot_id"));
            if(count($fieldArr) > 0) {
                $fieldArr = array_merge(array('id AS lot_id'), $fieldArr);
                $field = implode(',', $fieldArr);
            }
        }
        $rows = self::where($map)->pluck($field);
        if($rows && false !== strpos($field, "lot_url")) {
            $projectInfo = ProjectModel::getInfoByAppid($appid);
            if($projectInfo) {
                $caseTempName = $projectInfo['name'];
                foreach ($rows as &$row) {
                    if($row['lot_url'] && false === strpos($row['lot_url'], "/play/tpl_{$caseTempName}")) {
                        $row['lot_url'] = preg_replace("/^\/play\/(.*?)$/", "/play/tpl_{$caseTempName}/$1", $row['lot_url']);
                    }
                }
            }
        }
        return $rows;
    }
}
